class UsersController < ApplicationController
    include AuthenticatedSystemBrowse
  
    before_filter :login_required, :only => [ :edit, :update, :live, :life, :change_password, :update_icon, :connect, :disconnect, :rfriends, :invite ]
  
    def invite
        @page_title = '邀请朋友'
        return unless request.post?
        
        email_rex = /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
        
        if email_rex.match(params[:folk][:email1]).nil? && email_rex.match(params[:folk][:email2]).nil? && email_rex.match(params[:folk][:email2]).nil?
            flash[:notice] = '请输入至少一个完整的email地址!'
            redirect_to invite_users_url
        else
            folks = Array.new
            if !email_rex.match(params[:folk][:email1]).nil?
                folks << params[:folk][:email1]
            end
            
            if !email_rex.match(params[:folk][:email2]).nil?
                folks << params[:folk][:email2]
            end
            
            if !email_rex.match(params[:folk][:email3]).nil?
                folks << params[:folk][:email3]
            end
            
            #delete already exists user
            folks.each do |f|
                user = User.find_by_email(f)
                unless user.nil?
                    folks.delete(f)
                end
            end
            
            content = params[:letter][:content]
            
            #create Invitation, after three days, it should be expired.
            #update exists invitations
            #多个用户同时邀请一个怎么处理？
            folks.each do |f|
                @invitation = Invitation.find_by_email(f)
                unless @invitation.nil?
                    @invitation.update_attributes(:user_id => current_user.id, :invitation_code => Digest::SHA1.hexdigest( Time.now.utc.to_s.split(//).sort_by {rand}.join ), :expired_at => Time.now.utc + 3*24*3600)
                else
                    @invitation = Invitation.new(:user_id => current_user.id, :email => f, :invitation_code => Digest::SHA1.hexdigest( Time.now.utc.to_s.split(//).sort_by {rand}.join ), :expired_at => Time.now.utc + 3*24*3600)
                    @invitation.save!
                end
                UserNotifier.deliver_invite_folk(current_user, f, content, @invitation.invitation_code)
            end
            
            flash[:notice] = '邀请成功，你可以邀请更多的朋友加入!'
        end
    end
    
    def check_invite
        @invitation = Invitation.find_by_invitation_code(params[:id])
        
        if @invitation.nil? || @invitation.expired_at < Time.now.utc
            raise ActiveRecord::RecordNotFound
        end
        
        return unless request.post?
        
        User.transaction do
            friend = User.find(@invitation.user_id)
        
            @user = User.new(:login => params[:user][:login], :password => params[:user][:password], :password_confirmation => params[:user][:password], :email => @invitation.email, :community_id => 0, :activated_at => Time.now.utc, :activation_code => nil, :last_login_at  => Time.now.utc )
            @user.save!
        
            @user.become_friends_with friend
            friend.become_friends_with @user
        
            @invitation.destroy
        end
        
        self.current_user = @user
        self.current_user.remember_me
        cookies[:auth_token] = { :value => self.current_user.remember_token , :expires => self.current_user.remember_token_expires_at }
        flash[:notice] = "登陆成功.目前你还没有定居，在你定居之前不能在社区发布信息，但仍然可以参加小组，在论坛发帖。<a href='#{url_for(:controller => 'communities', :action => 'life')}'>马上定居!</a>"
        redirect_to(:controller => 'browse', :action => 'index')  
    end
    
    def connect
        @friend = User.find(:first, :conditions => ["id = ?", params[:id]])
        current_user.become_friends_with @friend
        render :text => "(我的好友)"
    end
  
    def disconnect
        user = User.find(:first, :conditions => ["id = ?", params[:id]])
        current_user.delete_friendship_with(user)
        redirect_to friends_user_url(current_user.login)
    end
  
    def login
        @page_title = '登录'
        if !params[:redir].nil?
            @referer = params[:redir]
        else
            @referer = request.referer
        end
        return unless request.post?
        if params[:login].blank?
            flash[:notice] = "请输入用户名."
            redirect_to login_users_path(:redir => @referer)
        elsif params[:password].blank?
            flash[:notice] = "请输入密码."
            redirect_to login_users_path(:redir => @referer)
        else
            self.current_user = User.authenticate(params[:login], params[:password])
            if current_user
                if params[:remember_me] == "1"
                    self.current_user.remember_me
                    cookies[:auth_token] = { :value => self.current_user.remember_token , :expires => self.current_user.remember_token_expires_at }
                end
                if params[:redir].nil?
                    redirect_back_or_default(:controller => 'browse', :action => 'index')
                else
                    if params[:redir] =~ /login|signup/
                        redirect_to(:controller => 'browse', :action => 'index')
                    else
                        redirect_to params[:redir]
                    end
                end
                session[:user] = current_user
                current_user.last_login_at = Time.now.utc
		current_user.save!
		if current_user.community.nil?
                    flash[:notice] = "登陆成功.目前你还没有定居，在你定居之前不能在社区发布信息，但仍然可以参加小组，在论坛发帖。<a href='#{url_for(:controller => 'communities', :action => 'life')}'>马上定居!</a>"
		else
                    flash[:notice] = "登陆成功."
                end
            else
                flash[:notice] = "登陆失败，请检查用户名，密码."
            end
        end
    end

    def signup
        @page_title = '注册'
        @user = User.new(params[:user])
        return unless request.post?
        @user.community_id = 0
        @user.save!
        #self.current_user = @user
        #self.current_user.remember_me
        #cookies[:auth_token] = { :value => self.current_user.remember_token , :expires => self.current_user.remember_token_expires_at }
        #redirect_to :controller => 'communities', :action => 'life'
        flash[:live] = "<p>你的帐户已启用, 感谢你对您这儿的支持。我们已经发送了一封激活邮件到你的信箱，请查看激活后马上开始你的社区生活！</p>"
        rescue ActiveRecord::RecordInvalid
        render :action => 'signup'
    end
  
    def logout
        self.current_user.disable_ferret
        self.current_user.update_attributes(:last_action_at => nil)
        self.current_user.forget_me if logged_in?
        cookies.delete :auth_token
        session[:user] = nil
        reset_session
        redirect_to request.referer #(:controller => 'browse', :action => 'index')
        #request.referer
    end
  
    def show
        @user = User.find_by_login(params[:id])
        if @user.nil?
            raise ActiveRecord::RecordNotFound
        else
            @friends = @user.friends_by_me
            @posts = @user.posts.find :all, :include => [:user], :order => "replied_at desc", :limit => "10"
            @tags = user_tags(@user.id)
            @talk = @user.talks.find(:first, :order => "created_at desc")
            @page_title = @user.display_name
	end
    end
    
    def replies
        @user = User.find_by_login(params[:id])
        if @user.nil?
            raise ActiveRecord::RecordNotFound
        else
            @friends = @user.friends_by_me
            @replies = @user.replies.find :all, :include => [:user, :post], :order => "replies.created_at desc", :limit => "10"
            @tags = user_tags(@user.id)
            @talk = @user.talks.find(:first, :order => "created_at desc")
            @page_title = @user.display_name
	end
    end
  
    def posts
        @user = User.find_by_login(params[:id])
        respond_to do |format|
            format.html do
                @posts = @user.posts.paginate :include => [:user], :order => "replied_at DESC", :page => params[:page]
                render :action => "posts.rhtml"
            end
            format.rss  do
                @posts = @user.posts.find(:all, :include => [:user], :order => "replied_at DESC", :limit => "15")
                render :action => "posts.rxml", :layout => false
            end
        end
    end
  
    def friends
        @user = User.find_by_login(params[:id])
        @friends = @user.friends_by_me
        @page_title = @user.display_name + '的好友'
    end
    
    def rfriends
        @user = User.find_by_login(params[:id])
        @friends = @user.friends_for_me
        @page_title = @user.display_name + '的好友'
    end
  
    def search
        if params[:q].nil? || params[:q].blank?
            redirect_back_or_default friends_users_url
        else
            @users = User.paginate_search(params[:q], {:page => params[:page]})
        end
    end
  
    #allow a user to edit their details
    def edit
        @user = current_user
        @talks_option = {"所有人可见" => 0, "仅好友可见" => 1, "所有人不可见" => 2}
        @notify_option = {"发送邮件通知" => 1, "不发送邮件通知" => 0}
        @page_title = '设置你的个人信息'
    end
  
    #update the user table
    def update
        @user = User.find(self.current_user.id)
        if @user.update_attributes(params[:user])
            flash[:notice] = '你的信息已经成功更新.'
            #redirect_to :controller => 'browse', :action => 'index'
        end
        redirect_to edit_user_url(current_user.login)
    end
  
    def update_icon
        current_user.image = params[:user][:image]
        current_user.disable_ferret
        current_user.save!
        flash[:notice] = '你的头像已经成功更新.'
        redirect_to edit_user_url(current_user.login)
    end
  
    def change_password
        @page_title = '更新你的密码'
        return unless request.post?
        if User.authenticate(current_user.login, params[:old_password])
            if (params[:password] == params[:password_confirmation])
             		current_user.disable_ferret
                current_user.password_confirmation = params[:password_confirmation]
                current_user.password = params[:password]
                flash[:notice] = current_user.save ? "修改密码成功" : "修改密码失败" 
            else
                flash[:notice] = "密码不匹配" 
                @old_password = params[:old_password]
            end
        else
            flash[:notice] = "密码错误" 
        end
    end
  
    def forgot_password
        return unless request.post?
        if @user = User.find(:first, :conditions => [ "email = ? and is_banned = 0", params[:email]])
         		@user.disable_ferret
            @user.forgot_password
            @user.save
            @welcome_text = "<p>密码修改链接已经发往你的邮箱,请到#{@user.email}查阅来自您这儿的邮件。</p><p>感谢你对您这儿的支持。</p>"
        else
            @welcome_text = "该邮箱没有被注册或用户被禁止" 
        end
        render :action => 'forgot_password'
    end

    def reset_password
        @user = User.find_by_password_reset_code(params[:id])
	raise if @user.nil?
        return if @user unless params[:password]
        if (params[:password] == params[:password_confirmation])
            self.current_user = @user #for the next two lines to work
            current_user.password_confirmation = params[:password_confirmation]
            current_user.password = params[:password]
            @user.reset_password
            flash[:notice] = current_user.save ? "密码已重置！" : "密码没有被重置！" 
        else
            flash[:notice] = "Password mismatch" 
        end  
        redirect_back_or_default(:controller => 'browse', :action => 'index') 
        rescue ActiveRecord::RecordInvalid
        logger.error "输入的用户密码的重置码无效！" 
        flash[:notice] = "输入的用户密码的重置码无效！请检查后重新输入！" 
        redirect_to forgot_password_users_url
    end

    def activate
	#@user = User.find_by_activation_code(params[:id])
	#if @user and @user.activate
	#	self.current_user = @user
	#	redirect_back_or_default(:controller => 'browse', :action => 'index')
	#	flash[:notice] = "Your account has been activated." 
	#end
	
	if params[:id]
            @user = User.find_by_activation_code(params[:id]) 
            if @user and @user.activate  
                self.current_user = @user
                redirect_back_or_default(:controller => 'browse', :action => 'index')
                flash[:notice] = "你的帐户已经被激活." 
            else
                flash[:error] = "未能激活你的帐户,请检查你的注册码." 
            end
        else
            flash.clear
        end
    end
end
